import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {AppGlobal, AppService} from "../../../services/app.service";
import {FileOpener} from "@ionic-native/file-opener"
import {FileTransfer, FileTransferObject} from "@ionic-native/file-transfer";
import {LoadingService} from "../../../services/loading.service";
import {AppConfig} from "../../../../app/app.config";
import {ResDataModel} from "../../../models/res-data-model";

/**
 * Generated class for the AppUpdatePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-app-update',
  templateUrl: 'app-update.html',
})
export class AppUpdatePage {

  platform:string;
  appVersion:string;

  constructor(public navCtrl: NavController,
              public viewCtrl: ViewController,
              public navParams: NavParams,
              private appService: AppService,
              private fileOpener:FileOpener,
              private transfer:FileTransfer,
              private loadingService: LoadingService) {
    this.platform = AppGlobal.platform;
    this.appVersion = AppGlobal.appVersion;
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad AppUpdatePage');
  }

  update(){
    alert("appVersion:" + AppGlobal.appVersion + " pkgName:" + AppGlobal.packageName);

    let postData = {
      info:{
        system:AppGlobal.platform.toUpperCase(),
        currentVersion:AppGlobal.appVersion,
      }
    };

    this.appService.httpPost('AppVersionCtrl_check',postData,null,(res:ResDataModel) => {
      var isLastest = res.datas[0].value;
      if(isLastest == "true"){
        this.appService.alert("当前已经是最新版本");
      } else {
        this.appService.confirm("有新的版本，是否下载？",()=>{
          //开始下载
          var url = AppConfig.ServerDomain+res.datas[1].value;
          this.download(url);
        },()=>{
          //不下载

        });
      }
    },true)
  }

  download(url:string){
    // this.fileOpener.open(AppGlobal.savePath+'/byte-of-python-chinese-edition.pdf', 'application/pdf')
    //   .then(() => alert('File is opened'),(err:any)=>alert('can not open the file!:'+JSON.stringify(err)))
    //   .catch(e => alert('Error openening file：' + e));
    const fileTransfer: FileTransferObject = this.transfer.create();

    //下载过程
    fileTransfer.onProgress(progressEvent => {
      var present = new Number((progressEvent.loaded / progressEvent.total) * 100);
      console.log('当前进度为：' + present.toFixed(0));
      var presentInt = present.toFixed(0);
      //显示加载框
      this.loadingService.presentProgress(presentInt);
    })

      console.log(AppGlobal.savePath + 'android.apk');
      var savePath = AppGlobal.savePath + 'android.apk';

    fileTransfer.download(encodeURI(url), savePath).then((entry) => {
      //alert('保存apk包的地址为: ' + AppGlobal.savePath + 'ionic3Demo-android.apk');
      alert('download complete!: ' + entry.toURL());
      //console.log("下载成功");
      this.fileOpener.open(entry.toURL(), "application/vnd.android.package-archive")
        .then(() => console.log('打开apk包成功！'))
        .catch(e => alert('打开apk包失败！'));
    }, (error:any) => {
      alert("下载失败:"+JSON.stringify(error));
      //this.loadingService.presentTip('操作提醒', '由于部分手机出现异常,请您进入手机设置-应用管理-Ceshiname-权限，将存储权限打开后再进行升级，由此给您带来的不便，敬请谅解。');
      for(var item in error) {
        console.log(item + ":" + error[item]);
      }
    }).catch((err:any) => {
      alert("失败:"+JSON.stringify(err));
    });

  }

  dismiss() {
    this.viewCtrl.dismiss();
  }
}
